package com.ios.util;

import net.coobird.thumbnailator.Thumbnails;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import static com.ios.util.PathUtil.getImgBasePath;

/**
*@Author:WenTao
*@Description:图片处理工具类
*@Date:11:06 2018/7/17
*/
public class ImageUtil {
    private static final Random r = new Random();
    private static final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyyMMddHHmmss");
    /*图片处理,返回图片存储路径*/
    public static String ThumbnailsImg(InputStream ImgInputStream,String fileName,String targetAddr) {
        /*获取文件拓展名*/
        String extension = getFileExtension(fileName);
        /*获取保存到服务器后的文件名*/
        String realFileName = getRandomFileName();
        /*创建目录*/
        makeDirPath(targetAddr);
        /*绝对路径*/
        String relativeAddr = targetAddr + realFileName + extension;
        /*建立图片文件*/
        File dest = new File(getImgBasePath() + relativeAddr);
        try{/*修改图片大小并存储*/
            Thumbnails.of(ImgInputStream)
                    .size(100,100)
                    .toFile(relativeAddr);
        }catch (IOException e){
            e.printStackTrace();
        }
        return relativeAddr;
    }

    /*获取输入文件流拓展名*/
    private static String getFileExtension(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));
    }
    /*生成新文件名**/
    private static String getRandomFileName(){
        /*当前修改时间加四位随机数*/
        int rannum = r.nextInt(8999) + 1000;
        String nowTimeStr = sDateFormate.format(new Date());
        return nowTimeStr + rannum;
    }
    /*创建目标路径所涉及的目录*/
    private static void makeDirPath(String targetAddr){
        String realFileParentPath = getImgBasePath() + targetAddr;
        File dirPath = new File(realFileParentPath);
        if (!dirPath.exists()){
            dirPath.mkdirs();
        }
    }

    /*删除图片*/
    public static void deleteFile(String url){
        File file = new File(url);
        if (file.exists()){
            if (file.isDirectory()){
                File files[] = file.listFiles();
                for (int i=0;i<files.length;i++){
                    files[i].delete();
                }
            }
            file.delete();
        }
    }
}

